import { useRef, useState } from 'react'

import { ITouchEvent, View } from '@tarojs/components'
import Taro from '@tarojs/taro'

import { Button, Field } from '@antmjs/vantui'

import { LoginFormData, LoginFormProps } from './interface'
import useCountDown from './useCountDown'
import isEmpty from '../../../../common/utils/isEmpty'
import { loginByPhoneApi, sendSmsCodeApi } from '../../api'

const phoneValid = (value?: string) => {
	if (!value || value === '') {
		return '手机号不能为空'
	}
	const pattern = new RegExp('^(\\+86)?1[3-9]\\d{9}$')
	if (!pattern.test(value)) {
		return '手机号格式不正确'
	}
	return ''
}

const smsCodeValid = (value?: string) => {
	if (!value || value === '') {
		return '验证码不能为空'
	}
	const pattern = new RegExp('^\\d{4}$')
	if (!pattern.test(value)) {
		return '验证码格式不正确'
	}
	return ''
}

const LoginForm = (props: LoginFormProps) => {
	const [autoLogin, setAutoLogin] = useState(true)
	const phoneRef = useRef('')
	const [formData, setFormData] = useState<LoginFormData>({
		phone: '',
		code: '',
		ticketId: ''
	})
	const [errors, setErrors] = useState<LoginFormData>({
		phone: '',
		code: ''
	})
	const { start, restSecond, counting, cancel } = useCountDown({ mis: 30 })

	const handleSmsCodeChange = (e?: ITouchEvent) => {
		const value = e?.detail
		setFormData({ ...formData, code: value })
		// 清空error
		setErrors({ code: '' })
		const validMessage = smsCodeValid(value)
		setErrors({ code: validMessage })
	}
	const handlePhoneChange = (e?: ITouchEvent) => {
		const value = e?.detail
		setFormData({ ...formData, phone: value })
		// 清空error
		setErrors({ phone: '' })
		const validMessage = phoneValid(value)
		setErrors({ phone: validMessage })
		// 输入新手机号码时暂停当下倒计时
		const needCountStop =
			counting && isEmpty(validMessage) && phoneRef.current != value
		if (needCountStop) {
			phoneRef.current = value
			cancel()
		}
	}

	const sendSmsCode = async () => {
		start()
		const result = await sendSmsCodeApi({ phone: formData.phone })
		setFormData({ ...formData, ticketId: result.ticketId })
	}
	/**
 * isLogin: true
loginDevice: "PC"
loginId: "1763004331302195201"
loginType: "login"
sessionTimeout: "-1"
tag: null
tokenActivityTimeout: "604800"
tokenName: "token"
tokenSessionTimeout: "-1"
tokenTimeout: "-1"
tokenValue: "650aa5ce-b008-4a45-80d6-8714c04d61c6"
 */
	const handlePhoneLogin = async () => {
		try {
			Taro.showLoading({ title: '登录中' })
			const result = await loginByPhoneApi(formData)
			if (result) {
				Taro.setStorageSync(`${result.tokenName}`, result.tokenValue)
				Taro.redirectTo({ url: '/pages/home/index' })
			}
		} finally {
			Taro.hideLoading()
		}
	}
	const sendCodeBtnText = !counting ? '发送验证码' : `${restSecond} 秒`
	return (
		<View {...props}>
			{autoLogin ? (
				<View>
					<Button type='info' block round>
						手机号快捷登录
					</Button>
					<Button
						plain
						type='info'
						block
						onClick={() => {
							setAutoLogin(false)
						}}
					>
						其他手机号登录
					</Button>
				</View>
			) : (
				<View>
					<Field
						center
						clearable
						placeholder='请输入电话号码'
						onChange={handlePhoneChange}
						errorMessage={errors.phone}
					/>
					<Field
						center
						clearable
						placeholder='请输入短信验证码'
						onChange={handleSmsCodeChange}
						errorMessage={errors.code}
						renderButton={
							<Button
								size='small'
								type='primary'
								onClick={sendSmsCode}
								disabled={!isEmpty(errors.phone) || counting}
							>
								{sendCodeBtnText}
							</Button>
						}
					/>
					<Button
						plain
						type='info'
						onClick={() => {
							setAutoLogin(true)
						}}
					>
						快捷登录
					</Button>
					<Button type='info' round block onClick={handlePhoneLogin}>
						确定登录
					</Button>
				</View>
			)}
		</View>
	)
}

export default LoginForm
